package com.aop.example.aspect;

import com.aop.example.annotation.Authority;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;


@Slf4j
@Component
public class AuthorityUtil {
    @Autowired
    StringRedisTemplate redisTemplate;

    public boolean checkAuth(Integer userId, String authority){
        if(userId == null || authority == null){
            log.warn("【日志信息】：检查匹配权限缓存时数据是否完整");
            return false;
        }
        String id = userId.toString();
        String key = RedisEnum.PERMISSION_AUTH_KEY.getPrefix() + id;
        Boolean member = null;
        try {
            member = redisTemplate.opsForSet().isMember(key, authority);
        } catch (Exception e) {
            log.warn("【日志信息】：权限匹配失败");
            return false;
        }
        return Boolean.TRUE.equals(member);
    }

    public boolean addAuth(Integer userId, List<String> permissionList){

        if (userId == null || permissionList == null || permissionList.isEmpty()) {
            log.warn("【日志信息】：检查添加权限缓存时数据是否完整");
            return false;
        }

        String id = userId.toString();
        String key = RedisEnum.PERMISSION_AUTH_KEY.getPrefix() + id;
        try {
            for (String permission : permissionList) {
                Long success = redisTemplate.opsForSet().add(key, permission);
                if(success == 0 ){
                   log.warn("【日志信息】：数据添加缓存失败（单条）,检查数据是否已存在"+permission);
                }
            }
            return true;
        } catch (Exception e) {
            log.warn("【日志信息】：数据添加缓存失败");
            return false;
        }
    }
}
